package cn.org.book.shop.tool.service;

import net.coobird.thumbnailator.Thumbnails;
import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * pdf转图片服务
 *
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-11-26 22:50
 * @Description:
 */
@Service
public class PdfToImageService {

    public static void pdf2Pic(String pdfPath, String path, String fileName) throws Exception {
        File fileOut = new File(path);
        if (!fileOut.exists()) {
            fileOut.mkdir();
        }
        Document document = new Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度
        float rotation = 0f;
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = (BufferedImage)
                    document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
            try {
                String imgName = fileName.concat("-").concat(i + ".png");
                File file = new File(path + imgName);
                ImageIO.write(image, "png", file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            image.flush();
        }
        document.dispose();
    }

    public static void picZip() throws IOException {
        String rootFolder = new File("").getAbsolutePath();
        Thumbnails.of(rootFolder + "/pdf/3.jpg")
                .scale(0.5f)
                .outputQuality(0.5f)
                .toFile(rootFolder + "/pdf/n3-zip.png");
    }

    /**
     * 按设置的宽度高度压缩图片文件<br> 先保存原文件，再压缩、上传
     *
     * @param oldFile 要进行压缩的文件全路径
     * @param newFile 新文件
     * @param width   宽度
     * @param height  高度
     * @return 返回压缩后的文件的全路径
     */
    public static void zipWidthHeightImageFile(File oldFile, File newFile, int width, int height) {
        try {
            Image srcFile = ImageIO.read(oldFile);
            String srcImgPath = newFile.getAbsoluteFile().toString();
            System.out.println(srcImgPath);
            String subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".") + 1);
            BufferedImage buffImg;
            if (subfix.equals("png")) {
                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            } else {
                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            }
            Graphics2D graphics = buffImg.createGraphics();
            graphics.setBackground(new Color(255, 255, 255));
            graphics.setColor(new Color(255, 255, 255));
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(srcFile.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
            ImageIO.write(buffImg, subfix, new File(srcImgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void pngYs(String filePath) {
        File path = new File(filePath);
        File[] files = path.listFiles();
        assert files != null;
        for (File file : files) {
            zipWidthHeightImageFile(file, file, 600, 450);
        }
    }

    public static void test() {
        File path = new File("F:\\JULY\\阅读绘\\pdf\\");
        File[] files = path.listFiles(File::isFile);
        Set<String> fileNameSet = new HashSet<>();
        for (File file : files) {
            fileNameSet.add(file.getName().substring(0, file.getName().indexOf(".")));
        }
        fileNameSet.forEach(PdfToImageService::createPng);
    }

    public static void createPng(String fileName) {
        String filePath = String.format("F:\\JULY\\阅读绘\\pdf\\%s.pdf", fileName);
        String imagePath = String.format("F:\\JULY\\阅读绘\\pdf\\%s-png\\", fileName);
        try {
            pdf2Pic(filePath, imagePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        pngYs(imagePath);
    }

    public static void main(String[] args) {
        test();
    }

}
